<template>
	<e-popup :show="show" @close="$emit('close')" round="32rpx">
		<view class="popup-box">
			<image class="close-btn img-40" :src="$staticPath('classify/close.png')" @tap.stop="$emit('close')"></image>
			<view class="sku-goods e-flex">
				<view class="e-m-r-30">
					<load-image mode="aspectFill" :size="['176rpx']" radius="10rpx" :src="checkInfo.skuCoverImg || goodsImg"></load-image>
				</view>
				<view>
					<slot name="price">
						<view class="price c-red fw-600">{{ $unitEn }}{{ checkInfo.price || goodsInfo.price }}</view>
					</slot>
					<view class="stock c-80" v-show="checkInfo.stock">{{ $t('classify.剩余') }} {{ checkInfo.stock }}{{ $t('classify.件') }}</view>
				</view>
			</view>
			<scroll-view scroll-y>
				<view class="sku-big-box" :style="{ '--backgroundColor': activeBackgroundColor }">
					<view class="sku-item-box" v-for="(item, index) in info.productSkus" :key="item.id">
						<view class="tlt">{{ item.name }}</view>

						<view class="item-box e-flex e-flex-wrap">
							<view
								class="item"
								:class="{ 'item-act': sitem.isCheck }"
								v-for="(sitem, sindex) in item.productSkuValues"
								:key="sitem.id"
								@tap="checkSku(index, sindex)"
							>
								{{ sitem.name }}
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="e-p-t-60" v-if="goodsForm">
				<goods-layout-form-popup
				ref="goodsLayoutFormPopupRef"
					:info="{ form: goodsForm, proId: goodsInfo.id, skuId: checkInfo.id }"
					:subType="1"
					:price="checkInfo.price || goodsInfo?.price || 0"
					:number="goodsNum"
					showStatus
					@edit="handleEditGoodsFormAnswerList"
				></goods-layout-form-popup>
			</view>
			<view class="sum-box e-flex e-flex-between">
				<view class="tlt">
					<text class="e-m-r-10">{{ $t('classify.请选择数量') }}</text>
					<text class="e-font-24 c-80" v-if="goodsInfo.maxNumber">({{ $t('classify.限购') + goodsInfo.maxNumber + $t('classify.件') }})</text>
				</view>
				<e-number-box :modelValue="goodsNum" @change="goodsNumChange"></e-number-box>
			</view>
			<view class="m-t-114">
				<e-button size="large" type="primary" shape="circle" :text="$t(btnText)" @click="confirm" :throttleTime="1000"></e-button>
			</view>
			<view style="height: 20rpx"></view>
		</view>
	</e-popup>
</template>

<script lang="ts" setup>
import { ref, computed, watch, nextTick } from 'vue';
import type { GoodsSkuSpecificationItem, GoodsForm } from '@/common/request/api';
import type { GoodsInfo, GoodsSkuInfo } from '../type';
import { useCurrentInstance } from '@/common/hooks';
import { arrayDeepClone } from '@/common/utils';
import type { LayoutFormModelValue,GoodsLayoutFormPopupInstance } from '@/typings';

const props = defineProps<{
	checkInfo: GoodsSkuSpecificationItem;
	info: GoodsSkuInfo;
	show: boolean;
	primary: string;
	goodsNum: number;
	goodsInfo: GoodsInfo;
	popupType: 1 | 2;
	defaultSkuId: string;
	goodsForm?: GoodsForm;
}>();

const emit = defineEmits(['close', 'update:goodsNum', 'update:info', 'update:checkInfo', 'update:skuId', 'buy', 'addCart', 'updateActivityData']);

const ctx = useCurrentInstance();

const goodsImg = computed(() => {
	return props.goodsInfo?.description.imgUrls ? props.goodsInfo?.description.imgUrls.split(',')[0] : '';
});

const activeBackgroundColor = computed(() => {
	return props.primary.replace('1)', '0.05)');
});

const btnText = computed(() => {
	return props.popupType === 1 ? 'classify.立即购买' : 'common.确定';
});

const goodsNumChange = (e: { value: string }) => {
	emit('update:goodsNum', Number(e.value));
	let goodsNum = Number(e.value);
	if (goodsNum <= props.goodsInfo.minimumPurchaseQty) {
		goodsNum = props.goodsInfo.minimumPurchaseQty;
	}
	if (Object.keys(props.checkInfo).length) {
		if (goodsNum > props.checkInfo.stock) {
			ctx.$toastApp(ctx.$t('classify.商品库存不足'));
			goodsNum = props.checkInfo.stock;
		}
	} else {
		ctx.$toastApp(ctx.$t('classify.请选择商品规格'));
		goodsNum = 1;
		return;
	}

	nextTick(() => {
		emit('update:goodsNum', goodsNum);
	});
};
const goodsLayoutFormPopupRef = ref<GoodsLayoutFormPopupInstance>()
const goodsFormAnswerList = ref<LayoutFormModelValue>([]);

const handleEditGoodsFormAnswerList = (list: LayoutFormModelValue) => {
	goodsFormAnswerList.value = list;
};

const confirm = async () => {
	if (props.checkInfo.stock == 0) {
		ctx.$toastApp(ctx.$t('classify.商品库存不足'));
		return;
	}
	if (props.goodsForm) {
		let status = true;
		if (props.goodsForm.formOptions.some((item) => 'hasRequired' in item && item?.hasRequired === 0) && goodsFormAnswerList.value.length === 0) {
			status = false;
		}
		if (!status) return;
		await goodsLayoutFormPopupRef.value?.submitGoodsForm(2)
		goodsFormAnswerList.value = []
	}
	emit(props.popupType === 1 ? 'buy' : 'addCart');
};

const checkList: Array<number | undefined> = [];

const checkSkuInfo = (productSkus: GoodsSkuInfo['productSkus']) => {
	productSkus.map((item, i) => {
		item.productSkuValues.map((sitem) => {
			if (sitem.isCheck) {
				checkList[i] = sitem.id;
			}
		});
	});
	// 选择的sku与商品的productSkus长度相同，则代表商品的每个规格都有选中
	if (checkList.length == productSkus.length && !checkList.includes(undefined)) {
		const checkInfo = props.info.productSkuSpecifications.find((item) => item.skuKey == checkList.join('/'));
		emit('update:checkInfo', checkInfo);
		emit('update:skuId', checkInfo?.id);
		emit('updateActivityData');
	}
	nextTick(() => {
		emit('update:goodsNum', props.goodsInfo.minimumPurchaseQty);
	});
};

const checkSku = (index: number, sindex: number) => {
	isResetCheckList = false;
	let productSkus = arrayDeepClone(props.info.productSkus);
	productSkus[index].productSkuValues.map((item) => {
		item.isCheck = false;
	});
	productSkus[index].productSkuValues[sindex].isCheck = true;
	emit('update:info', {
		...props.info,
		productSkus
	});
	checkSkuInfo(productSkus);
};
let isResetCheckList = true;

watch(
	() => props.info,
	(newValue) => {
		if (newValue.productSkus.length) {
			if (isResetCheckList) {
				let productSkus = arrayDeepClone(props.info.productSkus);
				productSkus.forEach((item) => {
					item.productSkuValues.map((items) => {
						items.isCheck = false;
					});
				});
				if (props.defaultSkuId) {
					let skuInfo = newValue.productSkuSpecifications.find((item) => item.id === props.defaultSkuId);
					skuInfo?.skuKey?.split('/').forEach((skuId, index) => {
						let skuIndex = productSkus[index].productSkuValues.findIndex((items) => `${items.id}` === skuId);
						if (skuIndex > -1) {
							productSkus[index].productSkuValues[skuIndex].isCheck = true;
						}
					});
				} else {
					productSkus.forEach((item) => {
						item.productSkuValues[0].isCheck = true;
					});
				}
				isResetCheckList = false;
				emit('update:info', {
					...newValue,
					productSkus
				});
				checkSkuInfo(productSkus);
			} else {
				isResetCheckList = true;
			}
		}
	}
);


</script>

<style lang="scss" scoped>
.m-t-114 {
	margin-top: 114rpx !important;
}

.c-80 {
	color: #808080;
}

.popup-box {
	padding: 52rpx 32rpx 0 32rpx;

	.sku-goods {
		padding-bottom: 20rpx;

		.price {
			@include fontH(48, 58);
		}

		.stock {
			@include fontH(28, 40);
		}
	}

	scroll-view {
		max-height: 570rpx;
	}

	.sku-big-box {
		.sku-item-box {
			margin-top: 64rpx;

			.tlt {
				color: #424242;
				@include fontH(30, 42);
			}

			.item-box {
				// @include flex(start, center, wrap);

				.item {
					min-height: 56rpx;
					padding: 10rpx 30rpx;
					// color: $color;
					font-size: 28rpx;
					line-height: 40rpx;
					margin-top: 20rpx;
					margin-right: 20rpx;
					// text-align: center;
					background: #ededed;
					border-radius: 10rpx;
					border: 2rpx solid #ededed;

					input {
						height: 56rpx;
						width: 120rpx;
						border-radius: 8rpx;
						// color: $color;
						font-size: 28rpx;
						line-height: 56rpx;
					}
				}

				.item-act {
					color: var(--color-primary);
					background: var(--backgroundColor);
					border-color: var(--color-primary);
				}
			}
		}
	}

	.sum-box {
		margin-top: 50rpx;

		.tlt {
			color: #424242;
			@include fontH(30, 42);
		}

		.sum-item {
			font-size: 30rpx;

			.number {
				width: 84rpx;
				height: 44rpx;
				line-height: 44rpx;
				background: #f2f2f2;
				border-radius: 4px;
			}
		}
	}

	.close-btn {
		position: absolute;
		top: 40rpx;
		right: 32rpx;
	}
}
</style>
